import { Component, OnInit } from '@angular/core';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { ApiService } from '@core/services/http/api.service';
import { BiService } from '../../../bi.service';

@Component({
  selector: 'internal-association',
  templateUrl: './internal-association.component.html',
  styleUrls: ['./internal-association.component.scss'],
})
export class InternalAssociationComponent implements OnInit {

  // 内协分析

  // 效率
  effectivenessField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  effectivenessModel: any = {};

  // 柱形图
  effectivenessBarOption: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['单量', '平均耗时'],
    },
    xAxis: {
      type: 'category',
    },
    yAxis: [
      {
        name: '单量',
        type: 'value',
        axisLabel: {
          formatter: '{value} 单',
        },
      },
      {
        name: '耗时',
        type: 'value',
        axisLabel: {
          formatter: '{value} 小时',
        },
      },
    ],
    series: [
      { name: '单量', type: 'bar', label: { show: true } },
      { name: '平均耗时', type: 'line', yAxisIndex: 1},
    ],
  };
  effectivenessBarData: any;
  effectivenessBarLoading: boolean = false;

  // 表格
  effectivenessFromData: any;
  effectivenessFromLoading: boolean = false;

  // 基地
  baseField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'month',
        },
        divCol: 5,
      },
    },
  ];
  baseModel: any = {};

  // 饼图
  basePieOption: any = {
    tooltip: {
      trigger: 'item',
      formatter: this.showTooltip,
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll',
    },
    series: [
      {
        name: '基地占比', type: 'pie', center: ['60%', '50%'], radius: '50%', emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  basePieData: any;
  basePieLoading: boolean = false;

  // 柱形图
  baseBarOption: any = {
    // title: {
    //   subtext: '客诉排序TOP20',
    //   left: 'left',
    // },
    tooltip: {
      trigger: 'item',
      formatter: this.showRankTooltip,
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    series: [
      { name: '基地', type: 'bar', sort: 'none', label: { show: true } },
    ],
  };
  baseBarData: any;
  baseBarLoading: boolean = false;

  constructor(
    private apiService: ApiService,
    private bi: BiService,
  ) {

  }

  ngOnInit() {
    setTimeout(() => {
      this.refreshEffectivenessData();
      this.refreshBaseData();
    }, 1000);
  }

  showTooltip(params) {
    let tooltip = params.seriesName + '<br/>' + params.name + ':' + params.data[1] + '(' + params.percent + '%)';
    return tooltip;
  }

  showRankTooltip(params) {
    let showText = '--';
    let oldT = params.data[2];
    if (params.data[2]) {
      let newT = params.data[1];
      let t;
      let type = 'noChange';
      if (oldT > newT) {
        t = oldT - newT;
        type = 'showDown';
      } else {
        t = newT - oldT;
        type = 'showUp';
      }
      if (t == 0 || type == 'noChange') {
        showText = '较上个月 持平';
      } else if (type == 'showUp') {
        showText = '较上个月 ↑' + t + '单';
      } else if (type == 'showDown') {
        showText = '较上个月 ↓' + t + '单';
      }
    }
    let tooltip = params.seriesName + '<br/>' + params.name + ' : ' + params.data[1] + ' ( ' + showText + ' )';
    return tooltip;
  }

  refreshEffectivenessData() {
    let date = this.bi.conversionMonths(this.effectivenessModel['DATE'],6);

    const data = {
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let barApi = 'fn.innerAssistService.innerEfficiencyBar';

    this.effectivenessBarLoading = true;
    this.apiService.post(barApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      console.log('内协效率分析-柱形图', body);
      // let dimensions = [];
      let source = [['time','amount','consume']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(res['INSURANCE_COMPANY']);
          source.push([
            res['time'],
            res['amount'],
            res['consume'],
          ]);
        });
      }
      this.effectivenessBarData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };
      this.effectivenessBarLoading = false;
    });

    let formApi = 'fn.innerAssistService.innerEfficiencyGrid';

    this.effectivenessFromLoading = true;
    this.effectivenessFromData = [];
    this.apiService.post(formApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      console.log('内协效率分析-表格', body);
      if (body && body.length != 0) {
        this.effectivenessFromData = body;
      }
      this.effectivenessFromLoading = false;
    });
  }

  refreshBaseData() {
    let date = this.bi.conversionMonth(this.baseModel['DATE']);
    let nowDate = this.bi.currentMonthsList(date);

    const data = {
      DATE_START: nowDate[0],
      DATE_END: nowDate[1],
    };

    let pieApi = 'fn.innerAssistService.innerBasePie';

    this.basePieLoading = true;
    this.apiService.post(pieApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      console.log('内协基地统计-饼图', body);
      let dimensions = [];
      let source = [];
      if (body && body.length != 0) {
        body.forEach((res) => {
          dimensions.push(res['baseName']);
          source.push([
            res['baseName'],
            res['percent'],
          ]);
        });
      }
      this.basePieData = {
        dataset: {
          dimensions: dimensions,
          source: source,
        },
      };
      this.basePieLoading = false;
    });

    let barApi = 'fn.innerAssistService.innerBaseGrid';

    this.baseBarLoading = true;
    this.apiService.post(barApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      console.log('内协基地统计-柱形', body);
      // let dimensions = [];
      let source = [['baseName','amount']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(res['INSURANCE_COMPANY']);
          source.push([
            res['baseName'],
            res['amount'],
            res['lastAmount'],
          ]);
        });
      }
      this.baseBarData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };
      this.baseBarLoading = false;
    });

  }

}

